import qaTable from '@/components/QuickAdminTable'
import Cookies from 'js-cookie'
export const curdMixin = {
    components: { qaTable },
    data () {
        return {
            // 表单禁用
            disabled: false,
            tableData: [],
            start_time: 0,
            logistics_count: 0,
            ismaterial_count: 0,
            dispute_count: 0,
            logistics_countz: 0,
            ismaterial_countz: 0,
            qustion_type: [],
            dispute_countz: 0,
            end_time: 0,
            // 查询表单数据
            findFormData: {},

            findFormData_logistics: {},
            editOpen_logistics: false,

            // 是否展示编辑
            editOpen: false,
            //是否展示搜索
            showSearch: true,
            //是否禁用
            multiple: true,
            // 总条数
            total: 0,
            // 分页参数
            pageInfo: {
                page: 1,
                limit: 10,
                sort: 'id',
                order: 'desc',
            },
            primaryKey: 'id',
            // 是否全屏
            isFullScreen: false,
            loading: false,
            exportLoading: false,
            exportLoading_achievement: false,
            exportLoading_achievementOrder: false,
            ids: [],
            ztotal_price: 0,
            yztotal_price: 0,
            yztotal_price_msg: "",
            freightx: "",
            materialx: "",
            zfreight_addition_w: "",
            qustype: [],
            options: [],
            table_customerjourney: [],
            zprofit: 0,
        }
    },

    methods: {
        // 全屏
        fullScreen () {
            this.isFullScreen = !this.isFullScreen
        },

        //打开编辑表单
        open () {
            this.editOpen = true
        },

        // 监听排序改变
        sortChange (val) {
            this.pageInfo.sort = val.sort
            this.pageInfo.order = val.order
            this.initIndex()
        },

        // 案列初始化列表
        initIndex () {
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.formatQueryParams(this.queryParams),
            }

            this.request
                .get(this.api.index, { params: qyparams })
                .then(response => {
                    let val
                    if (this.queryParams['key_words']) {
                        val = this.queryParams['key_words'].value
                    }
                    response.data.forEach(v => {
                        v.yyEditing = false
                        v.qdEditing = false
                        if (val) {
                            const matchs = v.landing_site.match(new RegExp(val, 'gi'))
                            if (matchs) {
                                v.landing_site = v.landing_site.replace(new RegExp(val, 'gi'), `<span style="color:#000;background-color:#ffff00">${matchs[0]}</span>`)
                            }
                        }
                    })
                    this.tableData = response.data
                    this.total = response.count
                    this.start_time = response.start_time
                    this.end_time = response.end_time
                    this.logistics_count = response.logistics_count
                    this.ismaterial_count = response.ismaterial_count
                    this.dispute_count = response.dispute_count
                    this.logistics_countz = response.logistics_countz
                    this.ismaterial_countz = response.ismaterial_countz
                    this.qustion_type = response.qustion_type
                    this.dispute_countz = response.dispute_countz
                    this.ztotal_price = response.ztotal_price
                    this.yztotal_price = response.yztotal_price
                    this.yztotal_price_msg = response.yztotal_price_msg
                    this.freightx = response.freightx
                    this.materialx = response.materialx
                    this.zfreight_addition_w = response.zfreight_addition_w
                    this.zprofit = response.zprofit
                    this.qustype = response.qustype
                    this.options = response.options
                    this.table_customerjourney = response.table_customerjourney
                    this.yyArr = response.tag_campaign || []
                    this.qdArr = response.tag_source || []
                })
                .finally(() => {
                    this.loading = false
                })
        },

        // 编辑
        handleEdit (row) {
            this.handleFind(row[this.primaryKey])
        },

        // 编辑回显
        async handleFind (id) {
            let response = await this.request.get(this.api.edit, { params: { id } })
            this.findFormData = this.formatFindData(response.data)
            this.editOpen = true
        },

        // 详情
        handleDetail (row) {
            this.handleFindDetail(row[this.primaryKey])
            this.disabled = true
        },

        // 详情回显
        async handleFindDetail (id) {
            let response = await this.request.get(this.api.find, { params: { id } })
            this.findFormData = this.formatFindData(response.data)
            this.editOpen = true
        },

        // 导出
        handleExport (row) {
            // 只导出已勾选的项
            const _columns = this.columns.filter(item => item.visible)
            const fields = _columns.map(item => {
                return { field: item.prop, comment: item.label }
            })

            let tableIds = row[this.primaryKey] || this.ids
            tableIds = tableIds.toString()
            const qyparams = {
                ...this.pageInfo,
                ...this.formatQueryParams(this.queryParams),
                fields: JSON.stringify(fields),
                tableIds: tableIds,
                output_id: this.$route.query.id
            }

            this.$confirm('是否确认导出所有数据项?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.exportLoading = true
                    return this.request.get(this.api.export, { params: qyparams, responseType: 'blob' })
                })
                .then(response => {
                    this.download(response, Cookies.get('filename') || 'file.xlsx')
                })
                .catch(err => { })
                .finally(() => {
                    this.exportLoading = false
                })
        },

        // 导出
        handleExport_sku () {
            // 只导出已勾选的项
            const _columns = this.columns.filter(item => item.visible)

            const qyparams = {
                ...this.pageInfo,
                ...this.formatQueryParams(this.queryParams),
                is_output: 1,
            }

            this.$confirm('是否确认导出?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.exportLoading = true
                    return this.request.get(this.api.export, { params: qyparams, responseType: 'blob' })
                })
                .then(response => {
                    this.download(response, Cookies.get('filename') || 'file.xlsx')
                })
                .catch(err => { })
                .finally(() => {
                    this.exportLoading = false
                })
        },

        // 导出
        handleExport_achievement (row) {
            // 只导出已勾选的项
            const _columns = this.columns.filter(item => item.visible)
            const fields = _columns.map(item => {
                return { field: item.prop, comment: item.label }
            })

            let tableIds = row[this.primaryKey] || this.ids
            tableIds = tableIds.toString()
            const qyparams = {
                ...this.pageInfo,
                ...this.formatQueryParams(this.queryParams),
                fields: JSON.stringify(fields),
                tableIds: tableIds,
                output_id: this.$route.query.id
            }

            this.$confirm('是否确认导出所有数据项?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.exportLoading_achievement = true
                    return this.request.get(this.api.export_achievement, { params: qyparams, responseType: 'blob' })
                })
                .then(response => {
                    this.download(response, Cookies.get('filename') || 'file.xlsx')
                })
                .catch(err => { })
                .finally(() => {
                    this.exportLoading_achievement = false
                })
        },
        // 导出
        handleExport_achievementOrder (row) {
            // 只导出已勾选的项
            const _columns = this.columns.filter(item => item.visible)
            const fields = _columns.map(item => {
                return { field: item.prop, comment: item.label }
            })

            let tableIds = row[this.primaryKey] || this.ids
            tableIds = tableIds.toString()
            const qyparams = {
                ...this.pageInfo,
                ...this.formatQueryParams(this.queryParams),
                fields: JSON.stringify(fields),
                tableIds: tableIds,
                output_id: this.$route.query.id
            }

            this.$confirm('是否确认导出所有数据项??', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.exportLoading_achievementOrder = true
                    return this.request.get(this.api.export_achievement_order, { params: qyparams, responseType: 'blob' })
                })
                .then(response => {
                    this.download(response, Cookies.get('filename') || 'file.xlsx')
                })
                .catch(err => { })
                .finally(() => {
                    this.exportLoading_achievementOrder = false
                })
        },
        //监听选中的table
        selectionChange (selection) {
            this.ids = selection.map(item => item[this.primaryKey])
            this.multiple = !selection.length
        },

        // 删除
        handleDelete (row) {
            let tableIds = row[this.primaryKey] || this.ids
            tableIds = tableIds.toString()
            this.$confirm(`是否确认删除表编号为"${tableIds}"的数据项?`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    return this.request.get(this.api.delete, { params: { id: tableIds } })
                })
                .then(() => {
                    this.initIndex()
                    this.msgSuccess('删除成功')
                })
                .catch(() => { })
        },

        //监听组件提交
        submitForm (formObj) {
            const filter_data = this.filterPostData(formObj, ['create_time', 'update_time'])
            if (formObj[this.primaryKey] != undefined) {
                filter_data.id = filter_data[this.primaryKey]
                this.request.post(this.api.edit, { ...filter_data }).then(response => {
                    this.msgSuccess('修改成功')
                    this.initIndex()
                    this.beforeClose()
                })
            } else {
                this.request.post(this.api.add, { ...filter_data }).then(response => {
                    this.msgSuccess('新增成功')
                    this.initIndex()
                    this.beforeClose()
                })
            }
        },

        //监听组件提交
        submitForm_order (formObj) {
            const filter_data = this.filterPostData(formObj, ['create_time', 'update_time'])
            if (formObj[this.primaryKey] != undefined) {
                filter_data.id = filter_data[this.primaryKey]
                this.request.post(this.api.edit, { ...filter_data }).then(response => {
                    this.msgSuccess('修改成功')
                    this.beforeClose()
                })
            } else {
                this.request.post(this.api.add, { ...filter_data }).then(response => {
                    this.msgSuccess('新增成功')
                    this.beforeClose()
                })
            }
        },
        submitSkuaddForm2 (formObj) {
            const filter_data = this.filterPostData(formObj, ['create_time', 'update_time'])
            if (formObj[this.primaryKey] != undefined) {
                filter_data.id = filter_data[this.primaryKey]
                this.request.post(this.api.skumanageadd, { ...filter_data }).then(response => {
                    this.msgSuccess('修改成功')
                    this.initIndex()
                    this.beforeSkuaddClose()
                })
            } else {
                this.request.post(this.api.skumanageadd, { ...filter_data }).then(response => {
                    this.msgSuccess('新增成功')
                    this.initIndex()
                    this.beforeSkuaddClose()
                })
            }
        },
        submitSkuForm2 (formObj) {
            const filter_data = this.filterPostData(formObj, ['create_time', 'update_time'])
            if (formObj[this.primaryKey] != undefined) {
                filter_data.id = filter_data[this.primaryKey]
                this.request.post(this.api.skumanage, { ...filter_data }).then(response => {
                    this.msgSuccess('修改成功')
                    this.initIndex()
                    this.beforeSkuClose()
                })
            } else {
                this.request.post(this.api.skumanage, { ...filter_data }).then(response => {
                    this.msgSuccess('新增成功')
                    this.initIndex()
                    this.beforeSkuClose()
                })
            }
        },
        //监听组件提交
        submitForm_number (formObj) {
            const filter_data = this.filterPostData(formObj, ['create_time', 'update_time'])
            if (formObj[this.primaryKey] != undefined) {
                filter_data.id = filter_data[this.primaryKey]
                this.request.post(this.api.edit_number, { ...filter_data }).then(response => {
                    this.msgSuccess('修改成功')
                    this.initIndex()
                    this.beforeClose_number()
                })
            } else {
                this.request.post(this.api.edit_number, { ...filter_data }).then(response => {
                    this.msgSuccess('新增成功')
                    this.initIndex()
                    this.beforeClose_number()
                })
            }
        },

        //监听组件提交
        submittf_applyForm (formObj) {
            const filter_data = this.filterPostData(formObj, ['create_time', 'update_time'])
            if (formObj[this.primaryKey] != undefined) {
                filter_data.id = filter_data[this.primaryKey]
                this.request.post(this.api.tf_apply, { ...filter_data }).then(response => {
                    this.msgSuccess('修改成功')
                    this.initIndex()
                    this.beforetf_applyClose()
                })
            } else {
                this.request.post(this.api.tf_apply, { ...filter_data }).then(response => {
                    this.msgSuccess('新增成功')
                    this.initIndex()
                    this.beforetf_applyClose()
                })
            }
        },
        //监听组件提交
        submitFormattr (formObj) {
            const filter_data = this.filterPostData(formObj, ['create_time', 'update_time'])
            if (formObj[this.primaryKey] != undefined) {
                filter_data.id = filter_data[this.primaryKey]
                this.request.post(this.api.editattr, { ...filter_data }).then(response => {
                    this.msgSuccess('修改成功')
                    this.initIndex()
                    this.beforeCloseattr()
                })
            } else {
                this.request.post(this.api.editattr, { ...filter_data }).then(response => {
                    this.msgSuccess('新增成功')
                    this.initIndex()
                    this.beforeCloseattr()
                })
            }
        },
        // 监听组件提交
        submitFormpurchase (formObj, purchase) {

            const filter_data = this.filterPostData(formObj, ['create_time', 'update_time'])
            console.log(formObj.sku.length, 6666)
            if (formObj.sku.length > 0 && purchase.length > 0) {
                filter_data.data = []
                if (purchase[0] == '批次号') {
                    purchase[0] = 'batch'
                } else if (purchase[0] == '审核状态') {
                    purchase[0] = 'status'
                } else if (purchase[0] == '申请人') {
                    purchase[0] = 'admin_id'
                } else if (purchase[0] == '颜色') {

                    purchase[0] = 'color'
                } else if (purchase[0] == 'create_time') {

                    purchase[0] = 'create_time'
                } else if (purchase[0] == '统计') {

                    purchase[0] = 'color_sum'
                } else {
                    purchase[0] = purchase[0]
                }
                filter_data.apply_type = this.activeName
                formObj.sku.forEach((i, num) => {
                    if (!formObj.sku[num][0]) {

                    } else {
                        filter_data.data.push({})
                        purchase.forEach((j, index) => {
                            console.log(purchase, filter_data.data, 8888)
                            filter_data.data[num][j] = formObj.sku[num][index]
                        })
                    }

                    // filter_data.data.push({this.purchase[0]:i[0],this.purchase[1]:i[1],this.purchase[2]:i[2],this.purchase[3]:i[3],this.purchase[4]:i[4],this.purchase[5]:i[5],this.purchase[6]:i[6],this.purchase[7]:i[7],this.purchase[8]:i[8],this.purchase[9]:i[9],this.purchase[10]:i[10],this.purchase[11]:i[11],this.purchase[12]:i[12],this.purchase[13]:i[13],this.purchase[14]:i[14],this.purchase[15]:i[15]}   
                    // filter_data.data.push({'color':i[0],'44C':i[1],'44D':i[2]})
                })
                this.request.post(this.api.addpurchase, { ...filter_data }).then(response => {
                    this.msgSuccess('新增成功')
                    this.initIndex()
                    this.beforeClosepurchase()
                })
                return
            }

            if (formObj[this.primaryKey] != undefined) {
                filter_data.id = filter_data[this.primaryKey]
                this.request.post(this.api.editpurchase, { ...filter_data }).then(response => {
                    this.msgSuccess('修改成功')
                    this.initIndex()
                    this.beforeClosepurchase()
                })
            } else {
                this.request.post(this.api.addpurchase, { ...filter_data }).then(response => {
                    this.msgSuccess('新增成功')
                    this.initIndex()
                    this.beforeClosepurchase()
                })

            }

        },

        //监听组件提交
        submitSkuForm (formObj) {
            this.msgSuccess('操作成功')
            this.initIndex()
            this.beforeSkuClose()
        },
        // 关闭sku弹窗监听
        beforetf_applyClose () {
            this.Opentf_apply = false
            this.disabled = false
            this.$refs['edittf_applyForm'].reset()
        },
        // 关闭弹窗监听
        beforeClose () {
            this.editOpen = false
            this.disabled = false
            this.$refs['editForm'].reset()
        },
        // 关闭sku弹窗监听
        beforeSkuClose () {
            this.skuOpen = false
            this.disabled = false
            this.$refs['editSkuForm'].reset()
        },
        // 关闭sku弹窗监听
        beforeSkuaddClose () {
            this.skuaddOpen = false
            this.disabled = false
            this.$refs['editSkuaddForm'].reset()
        },
        // 关闭sku弹窗监听
        beforeClosepurchase () {
            this.editpurchaseOpen = false
            this.disabled = false
            this.$refs['editForm'].reset()
        },
        // 关闭sku弹窗监听
        beforeClose_number () {
            this.editOpen_number = false
            this.disabled = false
            this.$refs['editForm_number'].reset()
        },
        // 关闭sku弹窗监听
        beforeCloseattr () {
            this.editOpenattr = false
            this.disabled = false
            this.$refs['editattrForm'].reset()
        },
        // 重置按钮操作
        resetQuery () {
            this.resetForm('queryForm')
            this.submitSearch()
        },

        // 搜索
        submitSearch () {
            this.pageInfo.page = 1
            this.initIndex()
        },

        //
        statusChange (row) {
            this.request.post(this.api.status, { id: row[this.primaryKey], status: row.new_switch }).then(() => {
                this.initIndex()
            })
        },

        //多窗口
        // 编辑
        handleEdit_logistics (row) {
            this.handleFind_logistics(row[this.primaryKey])
        },
        // 编辑回显
        async handleFind_logistics (id) {
            let response = await this.request.get(this.api.edit_logistics, { params: { id } })
            this.findFormData_logistics = this.formatFindData(response.data)
            this.editOpen_logistics = true
        },
        // 关闭弹窗监听
        beforeClose_logistics () {
            this.editOpen = false
            this.disabled = false
            this.$refs['editForm'].reset()
        },
        //监听组件提交
        submitForm_logistics (formObj) {
            const filter_data = this.filterPostData(formObj, ['create_time', 'update_time'])
            if (formObj[this.primaryKey] != undefined) {
                filter_data.id = filter_data[this.primaryKey]
                this.request.post(this.api.edit_logistics, { ...filter_data }).then(response => {
                    this.msgSuccess('修改成功')
                    this.initIndex()
                    this.beforeClose_logistics()
                })
            } else {
                this.request.post(this.api.edit_logistics, { ...filter_data }).then(response => {
                    this.msgSuccess('新增成功')
                    this.initIndex()
                    this.beforeClose_logistics()
                })
            }
        },
        // 关闭sku弹窗监听
        beforeClose_logistics () {
            this.editOpen_logistics = false
            this.disabled = false
            this.$refs['editForm_logistics'].reset()
        },

    },
}
